package com.ocp.macro.service.impl;

import com.ocp.macro.mapper.dealerAccount.DealerAccountMapper;
import com.ocp.macro.mapper.operate.OperateMapper;
import com.ocp.macro.entity.DealerAccount;
import com.ocp.macro.entity.Operate;
import com.ocp.macro.entity.UserInfoToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用于spring security 框架登录操作
 */
@Service
public class UserInfoTokenServiceImpl implements UserDetailsService {
    @Resource
    private OperateMapper operateMapper;
    @Resource
    private DealerAccountMapper dealerAccountMapper;

    /*用于spring security账户认证，username：账户名*/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String[] split = username.split("-"); // 获取用户名和登录身份
        UserInfoToken userInfoToken = null;
        if ("operate".equals(split[1])){// 运营人员登录
            Operate operate = operateMapper.selectOperateOne(split[0]);
            if (operate!=null)
                userInfoToken = new UserInfoToken(username,operate.getOptId(),
                        operate.getOptPwd(),operate.getUserEmail(),operate.getAuthorizations());
        }else if("dealer".equals(split[1])){ // 经销商人员登录
            DealerAccount dealerAccount = new DealerAccount();
            dealerAccount.setUserName(split[0]);
            dealerAccount = dealerAccountMapper.selectDealerAccountOne(dealerAccount);
            if (dealerAccount!=null)
                userInfoToken = new UserInfoToken(username,dealerAccount.getDealAccountId(),
                        dealerAccount.getDealPwd(),dealerAccount.getEmail(),dealerAccount.getAuthorizations());
        }
        if (userInfoToken==null)
            throw new UsernameNotFoundException("账号未找到");
        System.out.println(userInfoToken.toString());
        return userInfoToken;
    }
}
